angular度指令刷新参数更改

我有一个angular度指令是这样初始化的:

<conversation style="height:300px" type="convo" type-id="{{some_prop}}"></conversation> 

我希望它能够在$scope.some_prop更改时刷新指令,因为这意味着它应该显示完全不同的内容。

我已经testing过,没有任何反应,当$scope.some_prop改变时,链接函数甚至不会被调用。 有没有办法做到这一点?

链接function只被调用一次,所以它不会直接做你所期望的。 您需要使用angular度$watch来观察模型variables。

这款手表需要在链接function中设置。

如果你使用隔离范围作为指令,那么范围就是

scope :{typeId:'@' }

在你的链接function,然后你像添加一个手表

 link: function(scope, element, attrs) { scope.$watch("typeId",function(newValue,oldValue) { //This gets called when data changes. }); } 

如果你没有在some_prop上使用隔离的范围使用手表

你要做的是监视指令中属性的属性。 您可以使用$ observe()观察属性更改的属性,如下所示:

 angular.module('myApp').directive('conversation', function() { return { restrict: 'E', replace: true, compile: function(tElement, attr) { attr.$observe('typeId', function(data) { console.log("Updated data ", data); }, true); } }; }); 

请记住,我在这个指令中使用了“编译”function,因为你没有提到如果你有任何模型,并且这是否是性能敏感的。

如果你有模型,你需要改变“ 编译 ”function到“ 链接 ”或使用“ 控制器 ”,并监视模型更改的属性,你应该使用$ watch() ,并采取angular{{}}从属性括号,例如:

 <conversation style="height:300px" type="convo" type-id="some_prop"></conversation> 

在指令中:

 angular.module('myApp').directive('conversation', function() { return { scope: { typeId: '=', }, link: function(scope, elm, attr) { scope.$watch('typeId', function(newValue, oldValue) { if (newValue !== oldValue) { // You actions here console.log("I got the new value! ", newValue); } }, true); } }; }); 
 angular.module('app').directive('conversation', function() { return { restrict: 'E', link: function ($scope, $elm, $attr) { $scope.$watch("some_prop", function (newValue, oldValue) { var typeId = $attr.type-id; // Your logic. }); } }; } 

我希望这将有助于从父范围重新加载/刷新指令价值

 <html> <head> <!-- version 1.4.5 --> <script src="angular.js"></script> </head> <body ng-app="app" ng-controller="Ctrl"> <my-test reload-on="update"></my-test><br> <button ng-click="update = update+1;">update {{update}}</button> </body> <script> var app = angular.module('app', []) app.controller('Ctrl', function($scope) { $scope.update = 0; }); app.directive('myTest', function() { return { restrict: 'AE', scope: { reloadOn: '=' }, controller: function($scope) { $scope.$watch('reloadOn', function(newVal, oldVal) { // all directive code here console.log("Reloaded successfully......" + $scope.reloadOn); }); }, template: '<span> {{reloadOn}} </span>' } }); </script> </html>