Javascript 为什么在指令';用户界面上未反映s链接功能?
AngularJS指令“Javascript 为什么在指令';用户界面上未反映s链接功能?,javascript,angularjs,angularjs-directive,Javascript,Angularjs,Angularjs Directive,AngularJS指令“link函数更改隔离未反映在UI中的范围数据 以下是一个例子: var myApp = angular.module('myApp', []); myApp.directive('myDirective', function () { return { restrict: 'A', template: '<span>Title: {{myParams.title}}</span>', sco
link
函数更改隔离未反映在UI中的范围数据
以下是一个例子:
var myApp = angular.module('myApp', []);
myApp.directive('myDirective', function () {
return {
restrict: 'A',
template: '<span>Title: {{myParams.title}}</span>',
scope: {
myParams: '='
},
link: function ($scope) {
// the new value is not reflected in ui
$scope.myParams.title = 'this is myDirective';
}
};
});
var myApp=angular.module('myApp',[]);
myApp.directive('myDirective',function(){
返回{
限制:“A”,
模板:“标题:{{myParams.Title}}”,
范围:{
myParams:“=”
},
链接:功能($scope){
//新值不会反映在ui中
$scope.myParams.title='这是我的指令';
}
};
});
HTML:
我希望HTML页面显示这是我的指令
,但实际上它是这是标题
另外,你能解释一下为什么它会这样显示吗。感谢当
指令
初始化时,链接
功能只执行一次。
因此,链接
函数内部的myParams.title
值在此阶段分配(但稍后会被覆盖)
之后,您更新了属性中my params
的值(该值将被单独观察并由angular更新)。因此,属性中的值是myParam.title的最新值,并反映在UI中
如果要设置新值,可以在链接
中使用click函数(或其他事件处理程序),该函数可以如下更改值:
在控制器中:
$scope.myparams = {title: 'this is title'};
<div ng-app="app" ng-controller="Ctrl as ctrl">
<div my-directive my-params="{title: 'this is title'}"></div>
<div my-directive my-params="data"></div>
</div>
在UI中:
<div my-directive my-params="myparams"></div>
在指令中:
.directive('myDirective', function () {
return {
restrict: 'A',
template: '<span> Title: {{myParams.title}} </span>',
scope: {
myParams: '='
},
link: function ($scope,element) {
// the new value is not reflected in ui
element.click(function(){
$scope.myParams.title = 'this is myDirective';
$scope.$apply();
})
}
};
});
.directive('myDirective',函数(){
返回{
限制:“A”,
模板:“标题:{{myParams.Title}}”,
范围:{
myParams:“=”
},
链接:功能($scope,element){
//新值不会反映在ui中
元素。单击(函数(){
$scope.myParams.title='这是我的指令';
$scope.$apply();
})
}
};
});
原因是my params=“{title:'this is title'}”
是一个常量表达式,不可赋值。因此,即使您试图覆盖'title'
属性,它也会从常量中被覆盖回来。检查。它包含您的代码,并设置为使用Angular 1.4。不同的是,指令按上述方式使用一次,控制器使用一个可更改的非常量值使用一次:
$scope.myparams = {title: 'this is title'};
<div ng-app="app" ng-controller="Ctrl as ctrl">
<div my-directive my-params="{title: 'this is title'}"></div>
<div my-directive my-params="data"></div>
</div>
指令中给出的表达式(即
my params=“{title:'这是title'}”
)试图覆盖指令范围属性(总是在1.2中创建一个新对象,因此是无限摘要)。这是什么my params
?因为更新的值是属性中提供的值,在指定属性值之前,链接函数已经运行,因此属性值是最新的值。