我想在指令中将我的变量设为true。 问题是我的指令控制台正确但在视图中无法更改。 这是https://jsfiddle.net/yped7no0/
var app = angular.module('my-app', [], function () {
})
app.controller('AppController', function ($scope) {
$scope.test=true;
$scope.items = ["One", 'Two'];
})
app.directive('myDir', function () {
return {
restrict: 'E',
scope: {
myindex: '=',
myTest:'='
},
template:'<div>{{myindex}}</div>',
link: function(scope, element, attrs){
console.log('test', scope.myindex);
element.click(function(){
scope.myTest=false;
console.log(scope.myTest);
});
}
};
})
答案 0 :(得分:3)
请检查出来
var jimApp = angular.module("mainApp", []);
jimApp.controller('mainCtrl', function($scope){
$scope.test = true;
$scope.items = ["One", 'Two'];
})
.directive("myDir", function() {
return {
restrict : "E",
scope:{ myindex: '=', myTest:'=' },
template : "<div >Jimbroo{{myindex}} {{myTest}}</div>",
link: function(scope, element, attrs){
element.bind('click', function() {
scope.myTest = false;
scope.$apply();
});
}
};
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<div ng-app="mainApp" ng-controller="mainCtrl">
<div ng-repeat="item in items">
{{test}}
<my-dir myindex="$index" my-test="test" ></my-dir>
</div>
</div>
答案 1 :(得分:1)
这里是code updated
1 - 使用angularjs的更新版本 2 - 在指令中使用@
var app = angular.module(&#39; my-app&#39;,[],function(){
})
app.controller('AppController', function ($scope) {
$scope.test=true;
$scope.items = ["One", 'Two'];
})
app.directive('myDir', function () {
return {
restrict: 'E',
scope: {
myindex: '@',
myTest:'@'
},
template:'<div>{{myindex}}</div>',
link: function(scope, element, attrs){
console.log('test', scope.myindex);
element.click(function(){
scope.myTest=false;
console.log(scope.myTest);
});
}
};
})
<!DOCTYPE html>
<html ng-app="my-app">
<head lang="en">
<meta charset="utf-8">
<title>Custom Plunker</title>
<link rel="stylesheet" href="style.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="AppController">
<div ng-repeat="item in items track by $index">{{test}}
<my-dir my-test="test" myindex='{{$index}}'></my-dir>
</div>
</body>
</html>
答案 2 :(得分:1)
使用scope.$apply了解角度范围的变化 plnkr
var app = angular.module('my-app', [], function () {
})
app.controller('AppController', function ($scope) {
$scope.test=true;
$scope.items = ["One", 'Two'];
})
app.directive('myDir', function () {
return {
restrict: 'E',
replace: true,
scope: {
myindex: '@',
myTest:'@'
},
template:'<div>{{myTest}}</div>',
link: function(scope, element, attrs){
element.click(function(){
scope.$apply(function() {
scope.myTest=false;
console.log('called');
})
});
}
};
})