将AngularJS范围变量从指令传递到控制器的最简单方法是什么?我所看到的所有示例似乎都很复杂,难道没有一种方法可以从指令访问控制器并设置其作用域变量之一吗?
于2014/8/25编辑: 这是我分叉的地方。
谢谢@anvarik。
这是JSFiddle。我忘了我在哪里分叉。但这是一个很好的示例,向您展示了=和@之间的区别
<div ng-controller="MyCtrl"> <h2>Parent Scope</h2> <input ng-model="foo"> <i>// Update to see how parent scope interacts with component scope</i> <br><br> <!-- attribute-foo binds to a DOM attribute which is always a string. That is why we are wrapping it in curly braces so that it can be interpolated. --> <my-component attribute-foo="{{foo}}" binding-foo="foo" isolated-expression-foo="updateFoo(newFoo)" > <h2>Attribute</h2> <div> <strong>get:</strong> {{isolatedAttributeFoo}} </div> <div> <strong>set:</strong> <input ng-model="isolatedAttributeFoo"> <i>// This does not update the parent scope.</i> </div> <h2>Binding</h2> <div> <strong>get:</strong> {{isolatedBindingFoo}} </div> <div> <strong>set:</strong> <input ng-model="isolatedBindingFoo"> <i>// This does update the parent scope.</i> </div> <h2>Expression</h2> <div> <input ng-model="isolatedFoo"> <button class="btn" ng-click="isolatedExpressionFoo({newFoo:isolatedFoo})">Submit</button> <i>// And this calls a function on the parent scope.</i> </div> </my-component> </div> var myModule = angular.module('myModule', []) .directive('myComponent', function () { return { restrict:'E', scope:{ /* NOTE: Normally I would set my attributes and bindings to be the same name but I wanted to delineate between parent and isolated scope. */ isolatedAttributeFoo:'@attributeFoo', isolatedBindingFoo:'=bindingFoo', isolatedExpressionFoo:'&' } }; }) .controller('MyCtrl', ['$scope', function ($scope) { $scope.foo = 'Hello!'; $scope.updateFoo = function (newFoo) { $scope.foo = newFoo; } }]);