双向绑定在此示例中不起作用

时间:2016-06-21 20:43:41

标签: angularjs angular-directive

我是Angularjs的新手。有人可以帮助找到这个问题。双绑定在此示例中不起作用。

http://jsfiddle.net/gM2Hg/120/

<body ng-app="animateApp">
  <br/> the watch is triggered only on the load of the page, not on subsequent changes to the property "acts"
  <div ng-controller="tst">
    <input type="button" bn="" acts="acts" value="Add Action" /> {{acts.crop}}
  </div>
</body>

var animateAppModule = angular.module('animateApp', [])

animateAppModule.controller('tst', function($scope) {
  $scope.acts = {
    crop: "test"
  };
  $scope.$watchCollection('model.acts', function(newValue, oldValue) {
    alert("as");
  })
})

animateAppModule.directive('bn', function() {
  return {
    restrict: "A",
    scope: {
      acts: '='
    },
    link: function($scope, iElement, iAttrs) {
      alert("l");
      iElement.click(function() {
        alert($scope.acts.crop);
        $scope.acts = {
          crop: "real"
        };
        alert($scope.acts.crop);
      })
    }
  }
})

1 个答案:

答案 0 :(得分:2)

首先你必须写下这样的手表功能:

$scope.$watch('acts', function(newValue, oldValue) {
  alert("as");
});

现在,您在从指令更改范围后设置了应用:

$scope.$apply();

检查更新的jsFiddle:http://jsfiddle.net/gM2Hg/121/

希望这会对你有所帮助。感谢。