AngularJS从指令访问别名控制器属性

时间:2014-11-12 21:34:47

标签: angularjs

好的,这是一个人为的例子,但是......

说我有这样的控制器:

app.controller('TestCtrl', function() {
    this.testString;
    this.otherString;
});

我有一个这样的模板:

<div ng-controller='TestCtrl as test'>
    <input demo type='text' ng-model='test.testString'>
    {{test.otherString}}
</div>

然后我有这样的指示:

app.directive('demo', function() {
    return {
        require:'ngModel',
        link: function(scope, elem, attrs, ctrl) {

            scope.$watch(attrs.ngModel, function(newVal) {

                /* How do I get otherString without knowing the controller alias?
                   This works but is not good practice */
                scope.test.otherString = newVal + ' is cool!';

                /* This doesn't work, but would if the property was in scope 
                   instead of the controller */
                scope[attrs.demo] = newVal + ' is cool!';
            });
        }
    }
});

如何在不知道控制器别名的情况下获取otherString?我可以拆开attrs.ngModel来获取它,但是有一种“有角度”的方式来获得财产吗?

修改

虽然这个例子没有完全反映我在实际场景中遇到的问题,但我确实找到了如何在链接函数中获取控制器的属性,允许我更新模型:

        link: function(scope, elem, attrs, ctrl) {

            var otherString = scope.$eval(attrs.demo);              

            scope.$watch(attrs.ngModel, function(newVal) {
                otherString = newVal + ' is cool!';
            }
        }

2 个答案:

答案 0 :(得分:3)

指令应该对自身之外的任何事物都不了解。如果指令依赖于外部控制器已经定义了一些任意属性,事情将很容易破坏。

定义&#34;范围&#34;指令上的属性允许您公开用于将数据绑定到指令的显式API。

myModule.directive('demo', function() {
  return {
    scope: {
      demoString: '=demo',
    },
    link: function(scope, element, attrs) {
      // You can access demoString here, or in a directive controller.
      console.log(scope.demoString);
    }        
  };
});

和模板

<div ng-controller='TestCtrl as test'>
    <input demo="test.otherString" ng-model='test.testString'>
    {{test.otherString}}
</div>

这不是唯一的方式,以便于传递数据或设置绑定到指令,但这是最常见的方式,应涵盖大多数用例。

答案 1 :(得分:0)

如果你想要更像角度,我会在控制器中使用$ scope并将其传递给指令,如下所示:

app.directive('demo', function() {
  return {
    scope: {strings: '='},
    link: function(scope, elem, attrs, ctrl) {

        scope.$watch('strings.test', function(newVal) {

            /* How do I get otherString without knowing the controller alias? */
            scope.strings.other = newVal + ' is cool!';

        });
    }
}
});

然后在html:

   <div ng-controller='TestCtrl as test'>
      <input demo type='text' strings="strings" ng-model="strings.test" />
      {{strings.other}}
   </div>

在控制器中,您可以指定:

$scope.strings = {
    test: '',
    other: ''
}