Angularjs 无法从指令函数更新“scope”值
基本上,我使用的是服务来管理Angularjs 无法从指令函数更新“scope”值,angularjs,angular-directive,Angularjs,Angular Directive,基本上,我使用的是服务来管理弹出模式。由于我理解了使用服务的方法,因此无法在此处更新范围值 my service.js "use strict"; angular.module("tcpApp").service("modalService", function () { this.Name = "My Modal"; this.showModal = false; //default false. }); controller.js: $scope.modalServic
弹出模式
。由于我理解了使用服务
的方法,因此无法在此处更新范围
值
my service.js
"use strict";
angular.module("tcpApp").service("modalService", function () {
this.Name = "My Modal";
this.showModal = false; //default false.
});
controller.js:
$scope.modalService.Name = "Mo!" //changing the name works!
$scope.showModal = true; //changing the ng-show works!
这是我的指示:
"use strict";
var modalPopup = function ( modalService ) {
return {
restrict : "E",
replace : true,
scope : {
showModal:"=" //getting value from controller.js
},
templateUrl : "views/tools/modalPopup.html",
link : function ( scope, element, attrs ) {
scope.Name = modalService.Name; //if i remove this Name not working!
scope.hideModal = function () {
alert("i am called");
scope.showModal = false; //it's not updating the value!
}
}
}
}
angular.module("tcpApp")
.directive("modalPopup", modalPopup);
这是我在index.html
中的html:
<modal-popup ng-show="showModal" showModal="showModal"></modal-popup>
我正在单击hideModal()
,但是showmodel
没有变为false
,并且翘起模式没有关闭
这里的错误在哪里?我是如何错误地理解这里的服务的?或者正确的方法是什么
提前谢谢。您是否收到“我被呼叫”的警报?如果是,试试这个
alert("i am called");
scope.showModal = false; //it's not updating the value!
scope.$apply(); // add this line it will update scope object value
试试这个
scope.$apply(function() {
scope.showModal = false;
});
您不需要在视图中传递任何内容,因为您有一个服务设置可以为您执行此操作:
(函数(){
“严格使用”;
var app=角度模块(“tcpApp”,[]);
app.controller('someController',function($scope,modalService){
$scope.modal=modalService;
$scope.modal.Name=“Mo!”
});
app.service(“modalService”,function()){
this.Name=“我的模态”;
this.isOpen=false;
this.hide=函数(){
this.isOpen=false;
};
this.show=函数(){
this.isOpen=真;
};
});
})();
(功能(){
“严格使用”;
角度模块(“tcpApp”)指令(“modalPopup”,功能(modalService){
返回{
限制:“E”,
替换:正确,
作用域:{},
templateUrl:“modalPopup.html”,
链接:函数(范围、元素、属性){
scope.modal=modalService;
}
}
});
})();代码>
.ng模态{
位置:绝对位置;
排名:0;
左:0;
宽度:100%;
身高:100%;
}
.ng模式:之后{
内容:“;
显示:块;
位置:绝对位置;
身高:100%;
宽度:100%;
z指数:10;
背景色:rgba(0,0,0,0.2);
}
.ng模态对话框{
宽度:300px;
高度:150像素;
位置:绝对位置;
左:50%;
顶部:15px;
左边距:-150px;
z指数:100;
文本对齐:居中;
背景色:白色;
}
.ng模式关闭{
宽度:32px;
高度:32px;
线高:32px;
边界半径:50%;
背景色:红色;
保证金:5px自动;
}
显示模态
X
请测试我{{modal.Name}
ng单击
已管理摘要…这将抛出摘要进行中错误控制器或指令中没有任何内容正在使用服务this.showmodel
。您正在使用scope来设置本地控制器值,而不是使用scope:false,因此需要父控制器scope。我可能需要一些时间来集成它。请原谅我的迟疑。
scope.$apply(function() {
scope.showModal = false;
});