AngularJS : $scope.$watch is not updating value fetched from $resource on custom directive

后端 未结 4 423
无人共我
无人共我 2020-12-13 05:05

I\'m having an issue with custom directives that\'s driving me crazy. I\'m trying to create the following custom (attribute) directive:

angular.module(\'comp         


        
4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-13 05:33

    I had this problem too. It was due to the fact that my variable was at first not defined 'undefined' in the scope. Watch seems to not work on undefined variables. Seems obvious after-all.

    I was first trying to use watch to trigger when my variable would be effectively set by the controller. Example:

    myApp.controller('Tree', function($scope, Tree) {
    
    Tree.get({},
    function(data) { // SUCCESS
        console.log("call api Tree.get succeed");
        $scope.treeData = data;
    },
    
    function(data) { // FAILURE
        console.log("call api Tree.get failed");
        $scope.treeData = {};
    });
    });
    

    I solved it by initializing my variable with an empty object before calling the service:

    myApp.controller('Tree', function($scope, Tree) {
    
    $scope.treeData = {};      // HERE
    
    Tree.get({},
    function(data) { // SUCCESS
        console.log("call api Tree.get succeed");
        $scope.treeData = data;
    },
    
    function(data) { // FAILURE
        console.log("call api Tree.get failed");
        $scope.treeData = {};
    });
    });
    

    In that case watch was able to detect the change in the variable.

提交回复
热议问题