2016-03-02 40 views
0

我得到一些意外的行为,这是我第一次进入指令。角度组件指令和templateurl,对外部控制器的不同响应

我正在使用带有templateurl和隔离控制器的指令。我期待在templateurl中的dom基于dom(在这种情况下是select元素)和指令控制器之间的2路绑定作出反应。我在绑定属性上放置了一个'$ watch',该属性在第一次加载指令时触发。但是,如果用户选择不同的选项,它不会触发。这不是我迄今为止使用控制器的经验所能达到的正常功能。

我的指令如下:两次

(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

因此,我已经准备好了指令。看起来似乎还没有完全点击的角度文档中有一些基本的怪癖,并且更可能大多数IM仍然不是。

为了使它正常工作,我需要将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> 

但是,我还没有想出的一件事是,即使它的形容词按照预期模型化模型并更新视图 - 它仍然不会调用观察者..任何人都可以为我介绍一些这方面的知识吗?