angularjs 指令scope 绑定问题(directory scope binding)
都知道directory独立scope有三种映射方式(https://docs.angularjs.org/guide/directive),但当我想在link函数中使用controller(非父指令中的controller)的$scope属性时,总是映射失败,最后查到是向下面这样使用:
Controller: /* more code */ $scope.someObject = { name:'Umur', id:1 }; /* more code */
HTML: <my-directive my-attribute="someObject" />
Directive: { scope: {myValue: "=myAtrribute" }, link: function (scope, iElm, iAttrs) { var x = scope.myValue.name; // x == "Umur"; scope.myValue.name = "Kieslowski"; // if we go to parent scope (controller's scope, in this example) // $scope.someObject.name == "Kieslowski"; // would be true } }
以上是双向绑定方式,除此之外还有单项绑定和字符串绑定
单项绑定:
Controller: /* more code */ $scope.someObject = { name:'Umur', id:1 }; /* more code */ HTML: <my-directive my-attribute="someObject" /> Directive: { scope: {myValue: "&myAttribute"}, link: function (scope, iElm, iAttrs) { var x = scope.myValue(); // x == {name:"Umur", id:1} } }
text绑定:
JS: angular.module("myApp", []) .directive("myDirective", function () { return { restrict: "A", scope: { text: "@myText" } }; }).controller("myController", function ($scope) { $scope.foo = {name: "Umur"}; $scope.bar = "qwe"; }); HTML: <div ng-controller="myController"> <div my-directive my-text="hello {{ bar }}" </div> </div> Results: /* Directive scope */ in: $scope.text out: "hello qwe" // this would automatically update the changes of value in digest // this is always string as dom attributes values are always strings
参考文档:
https://umur.io/angularjs-directives-using-isolated-scope-with-attributes/
https://docs.angularjs.org/guide/directive
浙公网安备 33010602011771号