隔离范围无法监听值的变化

时间:2016-05-02 21:01:02

标签: angularjs

隔离范围设置为侦听包含范围中的更改。然而,这失败了。

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
  $scope.foo = { bar: 'hello' };

})
.directive('test-dir', function() {
  return {
    restrict: 'E',
    scope: {
      name: '='  
      },
      link: function($scope) {
        console.log($scope.name);

        $scope.$watch('name', function(newValue) {
          console.log(newValue);
        }, true);

      }
    };

});

模板是这样的:

  <body ng-controller="MainCtrl">
    <p>Hello {{foo.bar}}!</p>
    <input ng-model="foo.bar">

    <hr/>
    <testDir name='foo'></testDir>
  </body>

我在这里缺少什么?

Plnkr:http://plnkr.co/edit/kldjQrPPBFvlq7ZSOAeb?p=info

3 个答案:

答案 0 :(得分:2)

你的指令命名混淆了范围没有错:

.directive('testDir', function() {...

HTML:

<test-dir name='foo'></test-dir>

该指令首先没有工作

答案 1 :(得分:0)

应该有双引号而不是单引号:name="foo",而不是foo

还有驼峰案例命名用于声明。在引用它时,您应该使用短划线名称。

所以当你有像

这样的指令时
directive('testDir', function() {...});

然后你就像

一样使用它
<test-dir>

而不是<testDir>

答案 2 :(得分:0)

指令名称:

.directive('testDir', function() {........

html名称:

<test-dir name='foo'></test-dir>

还将范围名称更改为:

name: '=?'

如果不起作用:

name: '@' 
相关问题