angularjs – 使用ControllerAs与指令
发布时间:2020-12-17 08:13:55 所属栏目:安全 来源:网络整理
导读:我试图遵循John Papa的angularJS风格指南 here,并已经开始将我的指令转换为使用controllerAs。但是,这不行。我的模板似乎无法访问分配给vm的任何内容。看到这个非常简单的plnkr示例,展示了行为。 http://plnkr.co/edit/bVl1TcxlZLZ7oPCbk8sk?p=preview an
我试图遵循John Papa的angularJS风格指南
here,并已经开始将我的指令转换为使用controllerAs。但是,这不行。我的模板似乎无法访问分配给vm的任何内容。看到这个非常简单的plnkr示例,展示了行为。
http://plnkr.co/edit/bVl1TcxlZLZ7oPCbk8sk?p=preview angular .module('app',[]); angular .module('app') .directive('test',test); function test() { return { restrict: 'E',template: '<button ng-click="click">{{text}}</button>',controller: testCtrl,controllerAs: 'vm' } } angular .module('app') .controller('testCtrl',testCtrl); function testCtrl() { var vm = this; vm.text = "TEST"; }
当使用controllerAs语法时,您不会像通常那样访问$ scope,变量vm将添加到作用域,因此您的按钮需要变为:
< button ng-click =“click”> {{vm.text}}< / button> 注意vm。添加到文本的开头。 Here is a fork of your Plunk with the fix applied 问:你知道我将如何通过属性传递属性到指令,例如“scope:{text:’@’}”?然后我被迫在控制器上使用$ scope,并设置vm.text = $ scope.text? A:在你引用的文章中,有a section y075会谈到这种情况。看看bindToController: return { restrict: 'E',controllerAs: 'vm',scope: { text: '@' },bindToController: true // because the scope is isolated }; 那么你应该可以访问vm.text (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |