angularjs $ watch在指令中不起作用

时间:2016-09-08 09:04:59

标签: javascript angularjs

尝试使用单向绑定在指令中加载数据就是代码。

@reporting_masters_travel_requests = ReportingMastersTravelRequest.where(travel_request_id: @travel_request.id,status: nil)

@reporting_masters_travel_requests.each do |record|
  #Something like record.update record.save
end
#set a msg like no more records after loop
msg="No more records"

这里是指令

  <nav-directive depts="dummyData"></nav-directive>

APP.directive('navDirective', navDirective);
当conroller更新数据时,

scope.depts未定义。

2 个答案:

答案 0 :(得分:2)

语法$scope.$watch('someString')告诉Angular在给定的 someString中查看名为$scope 的变量的值。您可以在$rootScope上使用它,因此它将查找在rootScope上定义的变量depts,但由于depts仅在{{1}上定义,因此无法找到}。

所以只需使用scope

答案 1 :(得分:2)

试试这个,它的工作原理。使用scope.$watch

&#13;
&#13;
var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.dummyData = 'World';
});

app.directive('navDirective', function() {
return {
    restrict: "E",
    scope: { depts: '=' },
    template: '<div>test</div>',
    link: function(scope, elem, attr) {
            scope.$watch('depts', function(newVal, oldVal) {
            // or $watchCollection if students is an array
            if (newVal) {
               console.log('in Dir');
               console.log(scope.depts)
            }
        },true);


    }
};
});
&#13;
  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link href="style.css" rel="stylesheet" />
    <script data-semver="1.4.9" src="https://code.angularjs.org/1.4.12/angular.js" data-require="angular.js@1.4.x"></script>
    <script src="app.js"></script>
  </head>

  <body ng-app="plunker" ng-controller="MainCtrl">
   <nav-directive depts="dummyData"></nav-directive>
  depts value:  <input ng-model="dummyData"/> 
  </body>
&#13;
&#13;
&#13;