angularJS$watch在使用控制器更新数据时不在指令中工作

angularJS $watch do not work in directive when use controller to update data

本文关键字:指令 数据 工作 控制器 watch angularJS 更新      更新时间:2023-09-26

我有一个自定义指令,还有一个控制器将数据绑定到指令。

我从服务器部分获取数据,并将其绑定到指令。然而,当我更改范围变量时,我发现页面上指令的数据没有更新

这是我的代码

指令:

angular.module('MyApp')
.directive('stats',function() {
    return {
    templateUrl:'scripts/directives/dashboard/stats/stats.html',
    restrict:'E',
    replace:true,
    scope: {
    'comments': '@',
    'number': '@',
    'name': '@',
    'colour': '@',
    'details':'@',
    'type':'@',
    'goto':'@'
    },
  link : function($scope,element,attr){
    $scope.$watch('number', function(oldValue,newValue) {
           console.log(attr);  
        }, true);
  }
}
});

指令模板:

<div class="col-lg-3 col-md-6">
<div class="panel panel-{{colour}}">
    <div class="panel-heading">
        <div class="row">
            <div class="col-xs-3">
                <i class="fa fa-{{type}} fa-5x"></i>
            </div>
            <div class="col-xs-9 text-right">
                <div class="huge">{{number}}</div>
                <div>{{comments}}</div>
            </div>
        </div>
    </div>
    <a href="{{goto}}">
        <div class="panel-footer">
            <span class="pull-left">查看详情</span>
            <span class="pull-right"><i class="fa fa-arrow-circle-right"></i></span>
            <div class="clearfix"></div>
        </div>
    </a>
</div>

控制器:

'use strict';
angular.module('MyApp',['ngResource'])
.controller('MainCtrl', function($scope,$state,MyService) {
    $scope.result = {};
    var names = MyService.get({classtype:'getNames',start:'',end:''},function(){
        $scope.pages = names.data;
        if (typeof($scope.pages[0]) === 'undefined'){
            $scope.selectedItem = 'loading...';
        }else{
            $scope.selectedItem = $scope.pages[0].name;
        }
        var res = MyService.get({classtype:'getLastRes',seriesName:$scope.selectedItem},function(){
            $scope.result = res;
        });
    });
    $scope.dropboxitemselected = function(item){
        $scope.selectedItem = item;
        var result = MyService.get({classtype:'getLastRes',seriesName:item},function(){
            $scope.result = result;
        });
        //$scope.result = {};
    };

});

HTML:

<div class="row" ng-controller="MainCtrl">
    <stats number="{{result.score}}" comments="score" colour="primary" type="heartbeat" goto="#/res/{{result._id}}"></stats>
    <stats number="{{result.totalSize}}" comments="size" colour="primary" type="file-code-o" goto="#/res/{{result._id}}"></stats>
    <stats number="{{result.count}}" comments="count" colour="red" type="file-text" goto="#/res/{{result._id}}"></stats>
</div>

我的页面上有一个下拉框,当我通过控制器中的函数dropboxitemselected更改项目时,我需要刷新指令中的数据,我该怎么办?

我认为这是因为作用域绑定,应该使用'='进行双向绑定,而不是'@'。

scope: {
    'number': '=',
    },

在HTML中,去掉数字中的括号。

<stats number="result.score" comments="score" colour="primary" type="heartbeat" goto="#/res/{{result._id}}"></stats>