Angularjs:我可以让我的指令在控制器API回调后运行吗?

Angularjs: Can I have my directive run after controller API callback

本文关键字:回调 API 运行 控制器 我可以 我的 指令 Angularjs      更新时间:2023-09-26

首次发问者。如果我的术语不太对,我很抱歉,我刚接触angularjs

我有一个controller,它通过HTTP调用获得产品列表

contractManagementControllers.controller('PriceBandsCtrl', ['$scope', '$routeParams',     '$http', '$location',
    function ($scope, $routeParams, $http, $location)
    {
        $http.get('products').success(function (products)
        {
            $scope.productList = products
        })
    }

和一个我想访问该产品列表的directive

contractManagementControllers.directive("priceBands",function($http)
{
    return {
        scope: true,
        restrict: 'AE',
        replace: 'true',
        templateUrl: 'Partials/PriceBand.html',
        link: function ($scope, ele, attrs, c)
        {
            // use $scope.productList
        }
});

我的问题是事情发生的顺序。控制器函数首先运行,然后是指令链接函数,然后是设置产品列表的回调函数。因此,$scope.productList在指令链接函数中未定义,并给出错误

是否有办法强制链接函数等待,直到回调完成?

设置默认值为productList,以免出现未定义变量错误

contractManagementControllers.controller('PriceBandsCtrl', ['$scope', '$routeParams',     '$http', '$location',
    function ($scope, $routeParams, $http, $location)
    {
        $scope.productList = [];
        $http.get('products').success(function (products)
        {
            $scope.productList = products
        })
    }

,然后观察productList in指令的变化:

contractManagementControllers.directive("priceBands",function($http)
{
    return {
        scope: true,
        restrict: 'AE',
        replace: 'true',
        templateUrl: 'Partials/PriceBand.html',
        link: function ($scope, ele, attrs, c)
        {
            $scope.watch('productList', function(newValue, oldValue) {
                //Perform here if you need
            });
        }
});

无需在angularjs中等待callback。只要把$scope.productList=[];放在你的controller as first line里。它不会给指令undefined

在你的指令link function中只写$watch函数来观察元素的变化。