在$ scope内更新时,隔离范围绑定不起作用。$ watch

时间:2014-11-18 15:12:36

标签: javascript angularjs angularjs-directive angularjs-scope

为什么以下代码不起作用?我试图将x传递给指令,然后根据指令内部的x更新y的值。



var app = angular.module('app',[]);

app.controller('Ctrl', ['$scope', function($scope){
  $scope.x=[];
}]);

app.controller('dirCtrl', ['$scope', function($scope){
  $scope.y=[];
  
  $scope.click=function(){
    $scope.y.push({});
  }
  
  $scope.$watch('y', function(){
    $scope.x=$scope.y;
    console.log("$scope.x updated in $watch call");
  },true);
}]);
                           
app.directive('directive', [function(){
    return {
        restrict: 'E',
        scope: {
            x: '=',
        },
        template: '<div ng-controller="dirCtrl"><button ng-click="click()">clicky</button>y:{{y}}</div>'
    };
}]);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="Ctrl">
    <directive x='x'></directive>
    x:{{x}}
  </div>
</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

$scope.$watch()没有深入了解。 y引用本身永远不会改变,只是它的内容。请改用$scope.$watchCollection()

<强>更新

当您使用没有点表示法的绑定时,它最终会在$ scope内创建一个新插槽。诀窍是使用obj.x

之类的东西

查看所需的更改:

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

app.controller('Ctrl', ['$scope', function($scope){
  $scope.obj = {
    x: []
  };
}]);

app.controller('dirCtrl', ['$scope', function($scope){
  $scope.y=[];
  
  $scope.click=function(){
    $scope.y.push({});
  };

  $scope.$watch('y', function(){
    $scope.obj.x = $scope.y;
    console.log("$scope.obj.x updated in $watch call");
  },true);
}]);

app.directive('directive', [function(){
    return {
        restrict: 'E',
        scope: {
            obj: '=',
        },
        template: '<div ng-controller="dirCtrl"><button ng-click="click()">clicky</button>y:{{y}}</div>'
    };
}]);
&#13;
<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <script src="script.js"></script>
  </head>

  <body>
<div ng-app="app">
  <div ng-controller="Ctrl">
    <directive obj='obj'></directive>
    x: {{obj.x}}
  </div>
</div>
  </body>

</html>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您发送的数字不是对象,因此不受引用约束。 将它作为对象的属性,并将其传递给指令:

$scope.obj = {
    x: 5
};