angularjs:范围值未在视图中更新

时间:2015-02-08 23:58:45

标签: angularjs angularjs-scope angular-ng-if

detail.html文件中有按钮:

<div ng-controller="test.views.detail">
<div data-ng-repeat="item in details"  scroll>
    <button ng-click="showDetails(item)">The details</button>

in detail.js file

angular.module('test')
.controller('test.views.detail', function($scope) {

    $scope.detailsClicked = false;

    $scope.showDetails = function(item){
        $scope.detailsClicked = true;
    }....

在formDetail.html代码中:

<div ng-controller="test.views.detail">
{{detailsClicked}}
<div ng-if="detailsClicked">...

最初显示false有关详情点击,当我点击按钮时,它会转到showDetails函数,但$scope.detailsClicked的值永远不会更新!直截了当不确定为什么它不起作用:(

1 个答案:

答案 0 :(得分:3)

这是因为你在两个地方使用相同的控制器,并期望范围对象与它不相同。每次在标记中调用ng-controller时,都会创建一个新的范围对象。如果您希望它们基于相同的数据,那么请使用服务。

Here is an example

app.controller('test.views.detail', function($scope, detailsClicked) {

    $scope.detailsClicked = detailsClicked;

    $scope.showDetails = function(item){
        $scope.detailsClicked.isClicked = true;
    }
});

创建一个工厂/服务,保留数据,确保数据为

app.factory('detailsClicked', function(){
  var data = {
    isClicked: false
  }

  return data;
});