AngularJS:动态编译指令模板时适当的范围绑定
特定
>指令D1应用于元素E. 目的 > make指令D2对应用了D1的元素E的范围变化作出反应 的index.html <div ng-app="myApp" ng-controller="MainCtrl"> <label> <u>model: </u> <input type="text" ng-model="someValue" outer="tmpl.html"/> <hr/> </label> <script type="text/ng-template" id="tmpl.html"> <inner test="123"></inner> </script> <script src="angular.js"></script> app.js (function (ng) { var app = ng.module('myApp',[]); app.controller('MainCtrl',[ '$scope',function ($scope) { $scope.someValue = 'Hello,World!'; } ]) // directive D2 .directive('inner',function () { return { restrict: 'AE',replace: true,template: '<p>{{model || "N/A"}}</p>',scope: { model: '=ngModel' },link: function (scope,element,attrs) { scope.$watch('model',function (newValue,oldValue) { if (!ng.isDefined(oldValue) && !ng.isDefined(newValue)) { return; } // do stuff... }); } }; }) // directive D1 .directive('outer',[ '$templateCache','$compile',function ($templateCache,$compile) { return { restrict: 'AE',scope: {},attrs) { var template = $templateCache.get(attrs.outer); var compiled = $compile(template)(scope); element.parent().append(compiled); } }; } ]); })(angular); 小提琴 这里有一个过于简化的版本:http://jsfiddle.net/Nscp8/12/ 例 D1是一个弹出窗口小部件,可以配置为插入HTML作为其内容. 问题 ngModel绑定未正确完成,我没有从中获取更新.我在这做错了什么?
范围:{model:’= ngModel’}, 这会将属性模型绑定到内部元素的属性ng-model中定义的属性,因为您以元素的形式使用该指令.你的内部元素没有这样的属性. 但即使它有,第二个问题是内部的父范围是外部的范围,这也是一个孤立的范围. someValue在控制器的作用域中定义,因此无论您选择何种类型的绑定,内部都无法直接与someValue建立绑定. 解决方案取决于您的具体需求.有关可能的解决方案,请参见this fiddle. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |