在下面的代码中,我在单击“tab”元素时更改了对象的属性,但相应的ngbind span没有得到更新。我是否必须调用某些函数来更新视图?
HTML:
<html ng-app="splx">
...
<body ng-controller="Application">
<span ng-bind="obj.val"></span>
<tabpanel selector="obj">
<div tab value="junk">junk</div>
<div tab value="super">super</div>
</tabpanel>
</body>
</html>
JS:
var cf = angular.module('splx', []);
function Application($scope) {
$scope.obj = {val: "something"};
}
cf.directive('tabpanel', function() {
return {
restrict: 'AE',
scope: {
selector: '='
},
controller: ['$scope', function($scope) {}]
};
});
cf.directive('tab', function() {
return {
require: '^tabpanel',
restrict: 'AE',
scope: true,
link: function(scope, elem, attrs) {
elem.bind('click', function() {
scope.$parent.selector.val = "newthing";
});
}
};
});
答案 0 :(得分:2)
cf.directive('tab', function() {
return {
require: '^tabpanel',
restrict: 'AE',
scope: true,
link: function(scope, elem, attrs) {
elem.bind('click', function() {
scope.$apply(function () {
scope.$parent.selector.val = "newthing";
});
});
}
};
});
这对我有用。只是错过了一点范围。$在那里申请。
如果您发现自己正在使用/“申请已在进行中”,则可能需要查看https://coderwall.com/p/ngisma。
如果您想将值更改为您点击的内容,我会执行以下操作:
scope.$parent.selector.val = attrs.tab;
相反:
scope.$parent.selector.val = "newthing";
然后您可以将标记更改为:
<tabpanel selector="obj">
<div tab="junk">junk</div>
<div tab="super">super</div>
</tabpanel>
希望有所帮助!
答案 1 :(得分:1)
第一个问题:您没有将控制器绑定到您的应用。
您需要cf.controller('Application', Application);
。
此外,您需要在ng-controller="Application"
的父级和span
指令的HTML中使用tabpanel
。
第二个问题:在您需要click
事件中更改范围变量之后
scope.$apply()
让Angular知道某些内容发生了变化,需要$digest
。
您可以查看我的版本here。