我得到的一些行为在我第一次涉足指令时出乎意料。
我正在使用带有templateurl和隔离控制器的指令。我期待模板中的dom基于dom(在本例中为select元素)和指令控制器之间的双向绑定做出反应。我放了一块手表' $绑定属性,在首次加载指令时触发。但是,如果用户选择其他选项,则不会触发。到目前为止,这不是我对控制器体验所期望的正常功能。
我的指示如下:
(function () {
'use strict';
var projMgrApp = angular.module('projMgrApp')
.directive('elementStructure', function () {
var structureController = ['$location', '$scope', '$window', '_', '$http', 'isAdmin', 'pmElement',
'GetProject', 'Enums', 'Users',
function ($location, $scope, $window, _, $http, isAdmin, pmElement, GetProject, Enums, Users) {
/* Ive removed most code for simplification
*/
$scope.NewElementType = null;
$scope.$watch('NewElementType', function (val) { alert(val); })
}];
return {
restrict: 'EA',
scope: {
elementType: '@',
projectId: '@',
structureTemplate: '@'
},
controller: structureController,
templateUrl: '/partials/structure.html',
};
});
})();
在我的模板网址中,我有这个选择,我希望打电话给观察者..
<select class="form-control"
ng-options="d for d in ProductionCategoryOptions" ng-model="NewElementType"></select>
我将此指令作为单独的组件加载两次(而不是打算以共享任何值)
<fieldset class="tab-pane fade in" id="ProductionStructure">
<element-structure element-type="Production" project-id={{Project.Id}}" structure-template={{Project.ProjectSettings.SceneStructureTemplate}}"></element-structure>
</fieldset>
<fieldset class="tab-pane fade in" id="AssetStructure">
<element-structure element-type="Asset" project-id="{{Project.Id}}"></element-structure>
</fieldset>
答案 0 :(得分:0)
所以我的指令按预期工作。似乎角度文档中有一些基本的怪癖尚未完全点击,而且很可能大多数人仍未点击。
为了让它正常工作,我需要将一个ngmodel引入指令并以2方式绑定它('=')。在此之前,我在指令控制器中创建了“模型”,然后强制视图更新(甚至调用观察者 - 我猜测是范围问题)。所以相反,我在外部控制器中创建了模型,并将指令绑定到现在看起来像我想要的那样。
在我的外部控制器中,我创建了绑定到我的指令的对象:
$scope.ProductionStructureModel = {
Elements: null,
NewElement: {
Type: null,
Path: null,
Name: null,
Length: null,
Audio: null,
Parent: null,
}
};
我的指令然后引用如下:
return {
restrict: 'EA',
requires: '^^ngModel',
scope: {
elementType: '@',
projectId: '@',
structureTemplate: '@',
Model: '=ngModel',
},
controller: structureController,
templateUrl: '/partials/structure.html',
link: function (scope, element, attrs) {
scope.$watch('Model', function (val) {
alert(val);
console.log(val);
});
}
};
调用我的指令的html:
<element-structure element-type="Production" project-id="{{Project.Id}}"
structure-template="{{Project.ProjectSettings.SceneStructureTemplate}}"
ng-model="ProductionStructureModel"
></element-structure>
然而,有一点我还没想到,即使它按照预期调整模型并更新视图 - 它仍然没有调用观察者..有人能够为我阐明这一点吗?